<?php
namespace app\admin\controller;

use app\admin\validate\ManageGroupValidate;
use app\admin\validate\ManageInfoValidate;
use app\admin\validate\ManagePwdValidate;
use app\admin\validate\ManageValidate;
use app\common\controller\AdminBaseController;
use app\common\model\ManageGroupModel;
use app\common\model\ManageModel;
use think\facade\Cookie;
use think\Request;

/**
 *
 */
class ManageController extends AdminBaseController
{
    public function index()
    {
        $manage = cookie('admin_manage');
        // 关键词
        $keywords = $this->request->param('keywords');
        $this->assign('keywords', $keywords);

        // 搜索条件
        $where = [];
        $where[] = ['manage_status', '>=', '0'];
        if ($keywords != '') {
            $where[] = ['manage_username|manage_fullname|manage_phone|manage_email', 'like', '%' . $keywords . '%'];
        }
        if (!superman()) {
            $where[] = ['manage_id', 'not in', config('superid')];
        }
        $list = ManageModel::with('group')->where($where)->order('manage_id desc')
            ->paginate(20, false, ['query' => $this->request->param()]);
        $this->assign('list', $list);

        $group = ManageGroupModel::select();
        $this->assign('group', $group);
        return $this->fetch();
    }

    /**
     * 保存新增
     * @return [type] [description]
     */
    public function save(Request $request)
    {
        self::testPost();

        // 获取数据
        $data = $request->param();
        unset($data['manage_id']);

        // 验证数据
        $validate = new ManageValidate();
        if (!$validate->sceneCreate()->check($data)) {
            $this->error($validate->getError());
        }

        // 保存数据
        $field = ['manage_username', 'manage_password', 'manage_fullname', 'manage_email', 'manage_phone', 'manage_groupid', 'manage_status'];
        $manage = ManageModel::create($data, $field);
        if (!$manage) {
            $this->error('提示：新增失败!');
        }
        $this->success('恭喜：新增成功!', null, '', 1);
    }

    /**
     * 修改
     */
    public function edit($id)
    {
        $field = ['manage_id', 'manage_username', 'manage_fullname', 'manage_email', 'manage_phone', 'manage_groupid', 'manage_status'];
        $manage = ManageModel::field($field)->find($id);
        $this->success('恭喜：查询成功', null, $manage, 1);
    }

    /**
     * 保存修改
     */
    public function update(Request $request)
    {
        self::testPost();

        $data = $request->param();

        // 验证数据
        $validate = new ManageValidate();
        if (!$validate->sceneUpdate()->check($data)) {
            $this->error($validate->getError());
        }

        $manage = ManageModel::update($data);
        if (!$manage) {
            $this->error('提示：修改失败!');
        }

        $this->success('恭喜：修改成功!', null, '', 1);
    }

    /**
     * 删除
     */
    public function delete($id)
    {
        self::testDel();

        // $id 数据格式
        // $id：1
        // $id：1，2，3
        $manage = ManageModel::destroy($id);
        if (!$manage) {
            $this->error('提示：删除失败!');
        }
        $this->success('恭喜：删除成功!', null, '', 1);
    }

    /**
     * 审核
     */
    public function checked($id)
    {
        // $id 数据格式
        // $id：1
        // $id：1，2，3
        $where = 'manage_status=2 and manage_id in (' . $id . ')';
        $model = ManageModel::where($where)->update(['manage_status' => 1]);
        if (!$model) {
            $this->error('提示：审核失败!');
        }
        $this->success('恭喜：审核成功!', null, '', 1);
    }

    /**
     * 禁用
     */
    public function disable(Request $request, $id)
    {
        // $id 数据格式
        // $id：1
        // $id：1，2，3
        $model = ManageModel::where('manage_status=1 and manage_id in (' . $id . ')')->update(['manage_status' => 0]);

        if (!$model) {
            $this->error('提示：禁用失败!');
        }
        $this->success('恭喜：禁用成功!', null, '', 1);
    }

    /**
     * 启用
     */
    public function enable(Request $request, $id)
    {
        // $id 数据格式
        // $id：1
        // $id：1，2，3
        $model = ManageModel::where('manage_status=0 and manage_id in (' . $id . ')')->update(['manage_status' => 1]);
        if (!$model) {
            $this->error('提示：启用失败!');
        }
        $this->success('恭喜：启用成功!', null, '', 1);
    }

    /**
     * 重置密码
     */
    public function repwd(Request $request)
    {
        self::testPost();

        $data = [];
        $data['manage_id'] = $request->param('id');
        $data['manage_password'] = $request->param('pwd');
        $manage = ManageModel::update($data);
        if (!$manage) {
            $this->error('提示：重置密码失败!');
        }
        $this->success('恭喜：重置密码成功!', null, '', 1);
    }

    /**
     * 用户分组
     */
    public function group()
    {
        $keywords = $this->request->param('keywords', '');
        $this->assign('keywords', $keywords);
        $where = [];
        $where[] = ['group_id', '>', '0'];
        if ($keywords != '') {
            $where[] = ['group_name', 'like', '%' . $keywords . '%'];
        }
        $list = ManageGroupModel::where($where)->select();
        $this->assign('list', $list);
        return $this->fetch('manage/group/index');
    }

    /**
     * 获取分组权限规则
     * @return [type] [description]
     */
    public function group_action($id)
    {
        // 用户组
        $group = ManageGroupModel::field('group_id, group_action')->find($id);
        $action = $group->group_action;
        $action = explode(',', $action);

        // 处理
        $sites = self::getSites();
        $tree = array();
        foreach ($sites as $key => $site) {
            $menu = array();
            $path = $site['site_id'] . '-0';
            $menu[] = [
                'id' => $site['site_id'],
                'pId' => 0,
                'name' => '网站设置',
                'path' => $path,
                'checked' => in_array($path, $action),
            ];

            $columns = self::getColumns($site['site_id']);
            foreach ($columns as $key => $column) {
                $path = $site['site_id'] . '-' . $column['column_id'];
                $menu[] = [
                    'id' => $column['column_id'],
                    'pId' => $column['column_pid'],
                    'name' => $column['column_name'],
                    'path' => $path,
                    'open' => true,
                    'checked' => in_array($path, $action),
                ];
            }

            $tree[] = [
                'site_id' => $site['site_id'],
                'site_name' => $site['site_name'],
                'site_mark' => $site['site_mark'],
                'site_menu' => $menu,
            ];
        }

        // 系统栏目
        $tree[] = self::getSystemMenu($action);

        $this->assign('tree', $tree);
        $this->assign('group', $group);
        return $this->fetch('manage/group/action');
    }

    /**
     * 保存分组规则
     */
    public function group_action_save()
    {
        self::testPost();

        $group_id = $this->request->param('group_id');
        $group_action  = $this->request->param('group_action/a', '');
        $group_action = ($group_action != '') ? implode(',', $group_action) : '';
        
        ManageGroupModel::where('group_id', $group_id)->update(['group_action' => $group_action]);

        return $this->success('提示：分配成功', url('@admin/manage/group'), '', 1);
    }

    /**
     * 保存分组
     */
    public function group_save(Request $request)
    {
        self::testPost();

        // 获取数据
        $data = $request->param();

        // 验证数据
        $validate = new ManageGroupValidate();
        if (!$validate->check($data)) {
            $this->error($validate->getError());
        }

        // 保存数据
        $field = ['group_name'];
        $group = ManageGroupModel::create($data, $field);
        if (!$group) {
            $this->error('提示：新增失败!');
        }
        $this->success('恭喜：新增成功!', null, '', 1);
    }

    /**
     * 修改分组
     */
    public function group_update(Request $request)
    {
        self::testPost();

        $data = $request->param();
        // 验证数据
        $validate = new ManageGroupValidate();
        if (!$validate->check($data)) {
            $this->error($validate->getError());
        }

        $group = ManageGroupModel::update($data);
        if (!$group) {
            $this->error('提示：修改失败!');
        }
        $this->success('恭喜：修改成功!', null, '', 1);
    }

    /**
     * 删除分组
     */
    public function group_delete($id)
    {
        self::testDel();

        // $id 数据格式
        // $id：1
        // $id：1，2，3
        $group = ManageGroupModel::destroy($id);
        if (!$group) {
            $this->error('提示：删除失败!');
        }
        $this->success('恭喜：删除成功!', null, '', 1);
    }

    /**
     * 修改资料
     * @return [type] [description]
     */
    public function info()
    {
        // 用户信息
        $manage = cookie('admin_manage');
        $this->assign('admin_manage', $manage);
        return $this->fetch();
    }

    public function info_save(Request $request)
    {
        self::testPost();

        $manage = cookie('admin_manage');
        $data = [
            'manage_id' => $manage['manage_id'],
            'manage_fullname' => $request->param('manage_fullname'),
            'manage_phone' => $request->param('manage_phone'),
            'manage_email' => $request->param('manage_email'),
        ];

        // 验证数据
        $validate = new ManageInfoValidate();
        if (!$validate->check($data)) {
            $this->error($validate->getError());
        }

        // 修改数据
        $manage = new ManageModel;
        $result = $manage->do_info_save($data);
        if (!$result) {
            $this->error($manage->getError());
        }
        $this->success('恭喜：修改资料成功！', null, '', 1);
    }

    /**
     * 修改密码
     * @return [type] [description]
     */
    public function pwd()
    {
        return $this->fetch();
    }

    public function pwd_save(Request $request)
    {
        self::testPost();

        $data = array();
        $data['old_password'] = $request->param('old_password');
        $data['new_password'] = $request->param('new_password');
        $data['agn_password'] = $request->param('agn_password');
        // 验证数据
        $validate = new ManagePwdValidate();
        if (!$validate->check($data)) {
            $this->error($validate->getError());
        }

        $model = new ManageModel;
        $result = $model->do_pwd_save($data['old_password'], $data['agn_password']);
        if (!$result) {
            $this->error($model->getError());
        }
        return $this->success('恭喜：修改密码成功!下次登录请使用新密码。');
    }

    /**
     * 获取系统菜单
     * @Author   Yimao      [zjutsxj@qq.com]
     * @DateTime 2020-12-09
     * @param    array      $action          [description]
     * @return   [type]                      [description]
     */
    private function getSystemMenu($action = [])
    {
        return [
            'site_id' => 10000,
            'site_name' => '系统管理',
            'site_mark' => 'system',
            'site_menu' => [
                ['id' => 10001, 'pId' => 0, 'name' => '系统设置', 'path' => 'setting-index', 'open' => true, 'checked' => in_array('setting-index', $action)],
                ['id' => 1000101, 'pId' => 10001, 'name' => '系统信息', 'path' => 'setting-info', 'checked' => in_array('setting-info', $action)],
                ['id' => 1000102, 'pId' => 10001, 'name' => '数据库设置', 'path' => 'setting-db', 'checked' => in_array('setting-db', $action)],
                
                ['id' => 10002, 'pId' => 0, 'name' => '管理员列表', 'path' => 'manage-index', 'open' => true, 'checked' => in_array('manage-index', $action)],
                ['id' => 1000201, 'pId' => 10002, 'name' => '添加帐号', 'path' => 'manage-create', 'checked' => in_array('manage-create', $action)],
                ['id' => 1000202, 'pId' => 10002, 'name' => '修改帐号', 'path' => 'manage-edit', 'checked' => in_array('manage-edit', $action)],
                ['id' => 1000203, 'pId' => 10002, 'name' => '删除帐号', 'path' => 'manage-delete', 'checked' => in_array('manage-delete', $action)],
                ['id' => 1000204, 'pId' => 10002, 'name' => '重置密码', 'path' => 'manage-reset', 'checked' => in_array('manage-reset', $action)],
                ['id' => 1000204, 'pId' => 10002, 'name' => '审核账号', 'path' => 'manage-checked', 'checked' => in_array('manage-checked', $action)],
                ['id' => 1000205, 'pId' => 10002, 'name' => '禁用帐号', 'path' => 'manage-disable', 'checked' => in_array('manage-disable', $action)],
                ['id' => 1000206, 'pId' => 10002, 'name' => '用户分组', 'path' => 'manage-group', 'open' => true, 'checked' => in_array('manage-group', $action)],
                ['id' => 100020601, 'pId' => 1000206, 'name' => '添加', 'path' => 'group-create', 'checked' => in_array('group-create', $action)],
                ['id' => 100020602, 'pId' => 1000206, 'name' => '修改', 'path' => 'group-edit', 'checked' => in_array('group-edit', $action)],
                ['id' => 100020603, 'pId' => 1000206, 'name' => '删除', 'path' => 'group-delete', 'checked' => in_array('group-delete', $action)],
                ['id' => 100020604, 'pId' => 1000206, 'name' => '分配权限', 'path' => 'group-action', 'checked' => in_array('group-action', $action)],

                ['id' => 10003, 'pId' => 0, 'name' => '数据备份', 'path' => 'databk-index', 'open' => true, 'checked' => in_array('databk-index', $action)],
                ['id' => 1000301, 'pId' => 10003, 'name' => '新建备份', 'path' => 'databk-create', 'checked' => in_array('databk-create', $action)],
                ['id' => 1000302, 'pId' => 10003, 'name' => '下载备份', 'path' => 'databk-download', 'checked' => in_array('databk-download', $action)],
                ['id' => 1000303, 'pId' => 10003, 'name' => '删除备份', 'path' => 'databk-delete', 'checked' => in_array('databk-delete', $action)],

                ['id' => 10004, 'pId' => 0, 'name' => '主题管理', 'path' => 'theme-index', 'open' => true, 'checked' => in_array('theme-index', $action)],
                ['id' => 1000401, 'pId' => 10004, 'name' => '上传主题', 'path' => 'theme-upload', 'checked' => in_array('theme-upload', $action)],
                ['id' => 1000402, 'pId' => 10004, 'name' => '删除主题', 'path' => 'theme-delete', 'checked' => in_array('theme-delete', $action)],
                ['id' => 1000403, 'pId' => 10004, 'name' => '切换主题', 'path' => 'theme-switch', 'checked' => in_array('theme-switch', $action)],

                ['id' => 10005, 'pId' => 0, 'name' => '站点管理', 'path' => 'site-index', 'open' => true, 'checked' => in_array('site-index', $action)],
                ['id' => 1000501, 'pId' => 10005, 'name' => '新建站点', 'path' => 'site-create', 'checked' => in_array('site-create', $action)],
                ['id' => 1000502, 'pId' => 10005, 'name' => '站点参数', 'path' => 'site-param', 'checked' => in_array('site-param', $action)],
                ['id' => 1000503, 'pId' => 10005, 'name' => '修改站点', 'path' => 'site-edit', 'checked' => in_array('site-edit', $action)],
                ['id' => 1000504, 'pId' => 10005, 'name' => '删除站点', 'path' => 'site-delete', 'checked' => in_array('site-delete', $action)],
                ['id' => 1000505, 'pId' => 10005, 'name' => '栏目管理', 'path' => 'site-column', 'open' => true, 'checked' => in_array('site-column', $action)],
                ['id' => 100050501, 'pId' => 1000505, 'name' => '添加栏目', 'path' => 'column-create', 'checked' => in_array('column-create', $action)],
                ['id' => 100050502, 'pId' => 1000505, 'name' => '修改栏目', 'path' => 'column-edit', 'checked' => in_array('column-edit', $action)],
                ['id' => 100050503, 'pId' => 1000505, 'name' => '删除栏目', 'path' => 'column-delete', 'checked' => in_array('column-delete', $action)],
                ['id' => 100050504, 'pId' => 1000505, 'name' => '栏目参数', 'path' => 'column-param', 'checked' => in_array('column-param', $action)],

                ['id' => 10006, 'pId' => 0, 'name' => '模块管理', 'path' => 'module-index', 'open' => true, 'checked' => in_array('module-index', $action)],
                ['id' => 1000601, 'pId' => 10006, 'name' => '添加模块', 'path' => 'module-create', 'checked' => in_array('module-create', $action)],
                ['id' => 1000602, 'pId' => 10006, 'name' => '修改模块', 'path' => 'module-edit', 'checked' => in_array('module-edit', $action)],
                ['id' => 1000603, 'pId' => 10006, 'name' => '删除模块', 'path' => 'module-delete', 'checked' => in_array('module-delete', $action)],

                ['id' => 10007, 'pId' => 0, 'name' => '插件管理', 'path' => 'plugin-index', 'open' => true, 'checked' => in_array('plugin-index', $action)],
                ['id' => 1000701, 'pId' => 10007, 'name' => '添加插件', 'path' => 'plugin-create', 'checked' => in_array('plugin-create', $action)],
                ['id' => 1000702, 'pId' => 10007, 'name' => '修改插件', 'path' => 'plugin-edit', 'checked' => in_array('plugin-edit', $action)],
                ['id' => 1000703, 'pId' => 10007, 'name' => '删除插件', 'path' => 'plugin-delete', 'checked' => in_array('plugin-delete', $action)],
            ],
        ];
    }

}
